package com.nextpro.media.ui;

import com.nextpro.media.encoder.Encoder;
import com.nextpro.media.encoder.PlatFormEncoder;
import com.nextpro.media.file.MediaFileFilter;
import com.nextpro.media.interfaces.ProcessPublisher;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashSet;
import java.util.Set;


/**
 * Created by Administrator on 14-2-18.
 */
public class UIMediaFrame extends JFrame implements ActionListener, Runnable, ProcessPublisher {


    private JList<String> listFiles;
    private DefaultListModel<String> listModel;
    private JPanel panel;
    private JButton addFilesButton;
    private JButton startConvertButton;
    private JButton stopConvertButton;
    private JButton removeButton;
    private Thread thread;

    private Set<String> fileList = new HashSet<String>();
    private JProgressBar jProcessBar;
    private JLabel statusLabel;
    private int currentPercent;
    private int totalFiles = 0;
    private int finishedFiles = 0;


    public UIMediaFrame() throws HeadlessException {
        super("Media Converter");
        addmyMenu();
        initPanel();
        addProcessBar();
    }

    private void addProcessBar() {
        jProcessBar = new JProgressBar();
        statusLabel = new JLabel("Not Started");
        Box box = Box.createHorizontalBox();
        box.add(statusLabel);
        box.add(Box.createHorizontalGlue());
        box.add(jProcessBar);

        panel.add(box, BorderLayout.SOUTH);

    }

    private void initPanel() {
        this.panel = new JPanel();
        this.setContentPane(panel);
        panel.setLayout(new BorderLayout(10, 10));

        addList();
        addButtonPanel();
    }

    private void addmyMenu() {//Menu Bar
        JMenuBar menubar = new JMenuBar();//menu
        setJMenuBar(menubar);
        String menustr[] = {"File", "Help"};
        JMenu menu[] = new JMenu[menustr.length];//menuItem
        for (int i = 0; i < menustr.length; i++) {
            menu[i] = new JMenu(menustr[i]);
            menubar.add(menu[i]);
        }
        JMenuItem menuitem_exit = new JMenuItem("Exit");
        menu[0].add(menuitem_exit);
        menu[1].add(new JMenuItem("About"));
    }

    private void addList() {
        listModel = new DefaultListModel<String>();
        this.listFiles = new JList<String>(listModel);
        listFiles.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {

                if (listFiles.getSelectedIndices() != null && listFiles.getSelectedIndices().length != 0) {
                    removeButton.setEnabled(true);
                } else {
                    removeButton.setEnabled(false);
                }
            }
        });
        panel.add(listFiles, BorderLayout.CENTER);
    }

    private void addButtonPanel() {


        Box box = Box.createHorizontalBox();

        this.panel.add(box, BorderLayout.NORTH);

        box.add(Box.createHorizontalGlue());
        addFilesButton = new JButton();
        addFilesButton.setText("Add Files...");
        addFilesButton.addActionListener(this);
        box.add(addFilesButton);

        box.add(Box.createHorizontalGlue());
        removeButton = new JButton();
        removeButton.setText("Remove");
        removeButton.addActionListener(this);
        removeButton.setEnabled(false);
        box.add(removeButton);

        box.add(Box.createHorizontalGlue());
        startConvertButton = new JButton();
        startConvertButton.setText("Start");
        startConvertButton.addActionListener(this);
        startConvertButton.setEnabled(false);
        box.add(startConvertButton);

        box.add(Box.createHorizontalGlue());
        stopConvertButton = new JButton();
        stopConvertButton.setText("Stop");
        stopConvertButton.addActionListener(this);
        stopConvertButton.setEnabled(false);
        box.add(stopConvertButton);
        box.add(Box.createHorizontalGlue());


    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == addFilesButton) {
            JFileChooser jFileChooser = new JFileChooser();
            jFileChooser.setDialogTitle("Choose A File");
            jFileChooser.setFileSelectionMode(
                    JFileChooser.FILES_ONLY);
            jFileChooser.setMultiSelectionEnabled(true);
            jFileChooser.setFileFilter(new MediaFileFilter());
            jFileChooser.showOpenDialog(this);
            File[] files = jFileChooser.getSelectedFiles();
            for (File file : files) {
                fileList.add(file.getAbsolutePath());
            }
            startConvertButton.setEnabled(!fileList.isEmpty());
            listModel.clear();
            for (String filePath : fileList) {
                listModel.addElement(filePath);
            }
            listFiles.setModel(listModel);
        } else if (e.getSource() == removeButton) {
            java.util.List<String> indics = listFiles.getSelectedValuesList();
            if (indics != null) {
                for (String i : indics) {
                    fileList.remove(i);
                }
                startConvertButton.setEnabled(!fileList.isEmpty());
                listModel.clear();
                for (String filePath : fileList) {
                    listModel.addElement(filePath);
                }
                listFiles.setModel(listModel);
                removeButton.setEnabled(false);
            }
        } else if (e.getSource() == stopConvertButton) {
            if (thread != null) {
                thread.interrupt();
            } else {
                return;
            }

        } else if (e.getSource() == startConvertButton) {
            thread = new Thread(this);
            thread.start();
        }

    }

    @Override
    public void run() {

        this.addFilesButton.setEnabled(false);
        this.startConvertButton.setEnabled(false);
        this.stopConvertButton.setEnabled(true);
        Encoder encoder = PlatFormEncoder.createEncoder(this);
        int maxProcessValue = 0;
        if (!fileList.isEmpty()) {
            maxProcessValue = 100 * fileList.size();
        }
        jProcessBar.setMaximum(maxProcessValue);
        totalFiles = fileList.size();
        finishedFiles = 0;
		boolean ret = false;
        for (String filePath : fileList) {
            currentPercent = 0;
            ret = encoder.encode(filePath);
			if(ret != true){
				System.out.println("encode failed");
			}
            finishedFiles++;
        }
        jProcessBar.setValue(maxProcessValue);
        this.addFilesButton.setEnabled(true);
        this.startConvertButton.setEnabled(true);
        this.stopConvertButton.setEnabled(false);
        thread = null;
        statusLabel.setText("Finished");
    }

    @Override
    public void updateSpeed(String speed) {
        statusLabel.setText(String.format("%s %d/%d %d percent", speed, finishedFiles + 1, totalFiles, currentPercent));
//        System.out.println(speed);
    }

    @Override
    public void updateSingleProcess(int percent) {
        jProcessBar.setValue(jProcessBar.getValue() + percent);
        currentPercent += percent;
//        System.out.println(percent);
    }
}
